package com.mla.fastdfs.utils;

import cn.hutool.core.io.IoUtil;
import com.mla.fastdfs.commom.BaseException;
import com.mla.fastdfs.commom.UpLoadConstant;
import com.mla.fastdfs.entity.ZipMultipartFileParam;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;

@Slf4j
public class FileUtil {
    public static float maxSize = 1024 * 1024 * 2F;
    //public static float maxSize = 1024 * 1024F;

    /**
     * 保存压缩文件片段
     *
     * @param zipMultipartFile
     * @return
     */
    public static String saveZipPartFile(ZipMultipartFileParam zipMultipartFile) {
        String tempPath = UUID.randomUUID().toString().replace("-", "") + ".tmp";
        String filePath = UpLoadConstant.zipPartUpload + "/" + zipMultipartFile.getIdentifier();
        try {
            //创建片段临时文件夹
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(new File(filePath + "/" + tempPath));
            InputStream in = zipMultipartFile.getFile().getInputStream();
            int readBytes = 0;
            byte[] buffer = new byte[1024];
            //将文件流写入临时文件
            while ((readBytes = in.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, readBytes);
            }
            out.close();
            in.close();
            return filePath + "/" + tempPath;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public static void deleteDir(File file) {
        //判断是否为文件夹
        if (file.isDirectory()) {
            //获取该文件夹下的子文件夹
            File[] files = file.listFiles();
            //循环子文件夹重复调用delete方法
            for (int i = 0; i < files.length; i++) {
                deleteDir(files[i]);
            }
        }
        //若为空文件夹或者文件删除，File类的删除方法
        file.delete();
    }

    //文件拆分
    public static void getSplitFile(String file, List<String> path) {
        //预分配文件所占用的磁盘空间，在磁盘创建一个指定大小的文件，“r”表示只读，“rw”支持随机读写
        try {
            RandomAccessFile raf = new RandomAccessFile(new File(file), "r");
            //计算文件大小
            long length = raf.length();
            //计算文件切片后每一份文件的大小
            long count = (long) Math.ceil(length / maxSize);//计算切片数量

            long offset = 0L;//定义初始文件的偏移量(读取进度)
            //开始切割文件
            for (int i = 0; i < count; i++) { //count-1最后一份文件不处理
                //标记初始化
                long fbegin = offset;
                //分割第几份文件
                long fend = (i + 1) * (long) maxSize;
                //写入文件
                offset = getWrite(file, i, fbegin, fend, path);
            }
            raf.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    //文件写入
    public static long getWrite(String file, int index, long begin, long end, List<String> paths) {

        long endPointer = 0L;
        try {
            String tmpFile = file + "_" + index + ".tmp";
            //申明文件切割后的文件磁盘
            RandomAccessFile in = new RandomAccessFile(new File(file), "r");
            //定义一个可读，可写的文件并且后缀名为.tmp的二进制文件
            FileOutputStream out = new FileOutputStream(new File(tmpFile));

            //申明具体每一文件的字节数组
            byte[] b = new byte[1024];
            int n = 0;
            //从指定位置读取文件字节流
            in.seek(begin);
            //判断文件流读取的边界
            while (in.getFilePointer() <= end && (n = in.read(b)) != -1) {
                //从指定每一份文件的范围，写入不同的文件
                out.write(b, 0, n);
            }
            //定义当前读取文件的指针
            endPointer = in.getFilePointer();

            //关闭输入流
            in.close();
            //关闭输出流
            out.close();
            paths.add(tmpFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return endPointer;
    }

    /**
     * 使用NIO下载文件， 需要 jdk 1.7+
     *
     * @param url
     * @param saveDir
     * @param fileName
     */
    public static void downloadByNIO2(String url, String saveDir, String fileName) {
        try (InputStream ins = new URL(url).openStream()) {
            Path target = Paths.get(saveDir, fileName);
            Files.createDirectories(target.getParent());
            Files.copy(ins, target, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
       /* List<String> paths = new ArrayList<>();
        getSplitFile("D:\\5468250-6b452f31452ff07cb651876cc18d5c3b.mp4", paths);
        FileOutputStream out = new FileOutputStream(new File("D:\\mp4\\5468250.mp4"));
        int partNum=0;
        for (String path : paths) {
            InputStream in = new FileInputStream(new File(path));
            int readBytes = 0;
            byte[] buffer = new byte[1024];
            //将文件流写入临时文件
            while ((readBytes = in.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, readBytes);
            }
            in.close();
        }
        out.close();*/
        /*System.out.println(DateUtil.getStrTime());
        downloadByNIO2("http://apitest.yzrfish.com/img1/M00/00/04/ZwnDhGCClCGETqPWAAAAAMQy7Tc106.mp4", "D:\\", "观赏视频.mp4");
        System.out.println(DateUtil.getStrTime());*/
        String path = UpLoadConstant.zipPartUpload + "/"+UUID.randomUUID().toString().replace("-","")+"/5468250-6b452f31452ff07cb651876cc18d5c3b.MP4";
        System.out.println(path.substring(path.lastIndexOf(".")).toLowerCase());
        String a = path.substring(0, path.lastIndexOf("/"));
        String b = a.substring(a.lastIndexOf("/") + 1);
        System.out.println(b);
    }
}
